package main

import (
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/ulrichSchreiner/go-icap"
)

var ISTag = "\"ICAP SERVER\""

func main() {
	dir, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}

	http.Handle("/", http.FileServer(http.Dir(dir+"/sites")))

	r := initRouter()
	srv := &http.Server{
		Addr:    "192.168.1.43:8002",
		Handler: r,
	}
	go srv.ListenAndServe()

	icap.HandleFunc("/resq", recvHandle)
	icap.ListenAndServe(":11344", nil)
}

func initRouter() *gin.Engine {
	e := gin.Default()
	e.GET("/index", func(ctx *gin.Context) {
		ctx.JSON(http.StatusOK, gin.H{"data": "ok"})
	})
	return e
}

func recvHandle(w icap.ResponseWriter, req *icap.Request) {
	h := w.Header()
	h.Set("ISTag", ISTag)
	h.Set("Service", "ICAP Filter")
	if req.Method != "RESPMOD" {
		w.WriteHeader(405, nil, false)
		fmt.Println("Invalid request method")
	}

	if req.Method == "RESPMOD" {
		fmt.Println(req.Request.Host)
		if req.Request.Host == "192.168.1.43:8002" {
			w.WriteHeader(200, req.Request, false)
		} else {
			w.WriteHeader(204, nil, false)
		}
	}

}
